---
import { getCollection } from 'astro:content';
import Layout from '@/layouts/Layout.astro';
import Header from '@/components/Header.astro';
import Footer from '@/components/Footer.astro';
import LinkButton from '@/components/LinkButton.astro';
import Card from '@/components/Card.astro';
import Hr from '@/components/Hr.astro';
import IconArrowRight from '@/assets/icons/IconArrowRight.svg';
import config from '@/config';
import getPath from '@/utils/getPath';
import { getSortedPosts } from '@/utils/getPosts';

const posts = await getCollection('blog');

const sortedPosts = getSortedPosts(posts);
const pinnedPosts = sortedPosts.filter(({ data }) => data.pinned);
const recentPosts = sortedPosts.filter(({ data }) => !data.pinned);
---

<Layout>
  <Header />
  <main id="main-content">
    {
      pinnedPosts.length > 0 && (
        <>
          <section id="pinned" class="pt-12 pb-6">
            <h2 class="text-2xl font-semibold tracking-wide">Pinned</h2>
            <ul>
              {pinnedPosts.map(data => (
                <Card variant="h3" {...data} />
              ))}
            </ul>
          </section>
          {recentPosts.length > 0 && <Hr />}
        </>
      )
    }

    {
      recentPosts.length > 0 && (
        <section id="recent-posts" class="pt-12 pb-6">
          <h2 class="text-2xl font-semibold tracking-wide">Recent Posts</h2>
          <ul>
            {recentPosts.map(
              (data, index) => index < config.postPageSize && <Card variant="h3" {...data} />
            )}
          </ul>
        </section>
      )
    }

    <div class="my-8 text-center">
      <LinkButton href={getPath('posts')}>
        All Posts
        <IconArrowRight class="inline-block rtl:-rotate-180" />
      </LinkButton>
    </div>
  </main>
  <Footer />
</Layout>
